package com.example.easyutils.translation;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.easyutils.BaseActivity;
import com.example.easyutils.R;
import com.example.easyutils.curstartfortune.StartFortune;
import com.example.easyutils.httputil.HttpGetRequest;
import com.example.easyutils.logistics.TraceActivity;
import com.example.easyutils.util.DialogLoad;
import com.example.easyutils.util.InputDel;
import com.example.easyutils.util.MD5Utils;
import com.example.easyutils.util.MyTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zyao89.view.zloading.Z_TYPE;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class TranslationActivity extends BaseActivity {
     DialogLoad dialogLoad;
    private Uri playUri = null;
    private ImageView imageView,labaImageView;
    private Spinner spinner1,spinner2;
    private String langId1,langId2, textStr = "";
    private EditText transEditText;
    private TextView textView;
    private Map transMap;
    private static final int SUCCESS_CODE=1,ERROR_CODE = 2,PLAY_CODE = 3;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            dialogLoad.dialogCancel();
            switch (msg.what){
                case SUCCESS_CODE:
                    labaImageView.setVisibility(View.VISIBLE);
                    Log.d("map",transMap+"");
                    String resultTrans = ((Map)((List)transMap.get("trans_result")).get(0)).get("dst").toString();
                    textStr = resultTrans;

                    textView.setText(textStr);

                    //获取剪贴板管理器：
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
                    ClipData mClipData = ClipData.newPlainText("Label", resultTrans);
// 将ClipData内容放到系统剪贴板里。
                    cm.setPrimaryClip(mClipData);
                    break;
                case ERROR_CODE:
                    Toast.makeText(TranslationActivity.this,"出错",Toast.LENGTH_LONG).show();
                    break;
                case PLAY_CODE:
                    //直接创建，不需要设置setDataSource
                    Log.d("uri",playUri+"");


            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.translation_layout);
        spinner1 = (Spinner)findViewById(R.id.spinner1);
        spinner2 = (Spinner)findViewById(R.id.spinner2);
        transEditText = (EditText)findViewById(R.id.editext);
        textView = (TextView)findViewById(R.id.textView);
        labaImageView = (ImageView)findViewById(R.id.imageView3);
        dialogLoad = new DialogLoad(TranslationActivity.this);
//        Log.d("MD5",MD5Utils.digest("key毛扬能num4showapi_appid400982showapi_timestamptype202010211500002type2yayuntype218f9632e5e7e4c14b187790131ae8023"));
        InputDel inputDel = new InputDel(transEditText,imageView, TranslationActivity.this);
        inputDel.initListener();
        inputDel.editDel();
    }


    private void selectValue(String str,String str1){
        switch (str){
            case "自动检测":
                langId1 = "auto";
                break;
            case "中文":
                langId1 = "zh";
                break;
            case "英文":
                langId1 = "en";
                break;
            case "日文":
                langId1 = "jp";
                break;
            case "泰文":
                langId1 = "th";
                break;
            case "俄文":
                langId1 = "ru";
                break;
            case "德文":
                langId1 = "de";
                break;
            case "葡萄牙文":
                langId1 = "pt";
                break;
        }

        switch (str1){

            case "中文":
                langId2 = "zh";
                break;
            case "英文":
                langId2 = "en";
                break;
            case "日文":
                langId2 = "jp";
                break;
            case "泰文":
                langId2 = "th";
                break;
            case "俄文":
                langId2 = "ru";
                break;
            case "德文":
                langId2 = "de";
                break;
            case "葡萄牙文":
                langId2 = "pt";
                break;
        }
    }
    public void translateHttpRequest(View v){//请求接口
        dialogLoad.dialogLoaded("加载中...");
        String from1 = (String) spinner1.getSelectedItem();
        String from2 = (String) spinner2.getSelectedItem();
        selectValue(from1,from2);
        String text = transEditText.getText().toString();

        Log.d("testText",langId1+","+langId2+","+text);

//        try {
//            text =java.net.URLEncoder.encode(text,"utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//
//        String url = "http://api.avatardata.cn/Dictionary/Translate?key=7cfdf0a46f7f4a54a97e8e371ee6dd9e&" +
//                "query="+text+"&from="+langId1+"&to="+langId2;
        String url = "https://v1.alapi.cn/api/fanyi?q="+text+
                "&from="+langId1+"&to="+langId2;
        if(langId1==""){
            url = "https://v1.alapi.cn/api/fanyi?q="+text+"&to="+langId2;
        }
     //   https://v1.alapi.cn/api/fanyi?q=你好&from=zh&to=en
//        de 德文 jp日本 pt 葡萄牙文 ru 俄文 th 泰文
        HttpGetRequest.sendOkHttpGetRequst(url,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(ERROR_CODE);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();

                        Log.d("SUCCESS_QUERY",result);
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, Object>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,Object> dataDetail = gson.fromJson(result,new TypeToken<Map<String,Object>>(){

                        }.getType());

                        Long code = (Long) dataDetail.get("code");
                        transMap = new HashMap();
                        if(code==200){
                            transMap = (Map) dataDetail.get("data");
                            handler.sendEmptyMessage(SUCCESS_CODE);
                        }else{
                            handler.sendEmptyMessage(ERROR_CODE);
                        }
                    }
                });
    }

    public void read(View v){
//        https://api.vvhan.com/api/song?txt=

        textStr = textStr.replace(" ","_");
        Log.d("textstrs",textStr);
        playUri = Uri.parse("https://api.vvhan.com/api/song?txt="+textStr);
        MediaPlayer mMediaPlayer= MediaPlayer.create(TranslationActivity.this,playUri);
        mMediaPlayer.start();
//        handler.sendEmptyMessage(PLAY_CODE);
    }
}
